package myjava.i_collection;

/**
 * @Auther: cty
 * @Date: 2019/11/9 下午9:30
 * @Description:  自定义实现一个ArrayList
 * @version: 1.0
 */
public class D_MyArrayList <E>{
    private Object[] elementData;
    private int size;

    private static final int DEFAULT_CAPACITY = 10;

    public D_MyArrayList(){
        elementData = new Object[DEFAULT_CAPACITY];
    }

    public D_MyArrayList(int capicity) {
        if(capicity<0){
            throw new RuntimeException("容器容量不能为负数");  //不合法手动抛出异常
        }else if(capicity==0){
            elementData = new Object[DEFAULT_CAPACITY];
        }else{
            elementData = new Object[capicity];
        }
    }

    public void add(E element){
        //什么时候扩容
        if(size==elementData.length){
            //怎么扩容
            Object[] newArray = new Object[elementData.length+(elementData.length>>1)];  //注意：“+”的优先级高于“>>”
            System.arraycopy(elementData,0,newArray,0,elementData.length);
            elementData = newArray;
        }
        elementData[size++] = element;
    }

    public String toString(){
        StringBuilder sb = new StringBuilder();

        sb.append("[");
        for(int i=0;i<size;i++){
            sb.append(elementData[i]+",");
        }
        sb.setCharAt(sb.length()-1,']');

        return sb.toString();
    }

    public void checkRange(int index){
        if(index<0 || index>size-1){
            throw new RuntimeException("索引"+index+"不合法");  //不合法手动抛出异常
        }
    }

    public E get(int index){
        //索引合法判断
        checkRange(index);
        return (E)elementData[index];
    }

    public void set(E element,int index){
        //索引合法判断
        checkRange(index);
        elementData[index] = element;
    }

    public void remove(E element){
        //element 将和所有元素逐个比较，将第一个遇到的相同元素移除
        for(int i=0;i<size;i++){
            if(element.equals(get(i))){
                remove(i);
            }
        }
    }

    public void remove(int index){
        int numberMoved = size-index-1;
        if(numberMoved>0){
            System.arraycopy(elementData,index+1,elementData,index,numberMoved);
        }
        elementData[size-1] = null;
        size--;
    }

    public int size(){
        return size;
    }

    public boolean isEmpty(){
        return size==0?true:false;
    }


    public static void main(String[] args) {
        D_MyArrayList<String> s1 = new D_MyArrayList();

        for(int i=0;i<40;i++){
            s1.add("aa"+i);
        }
        System.out.println(s1);
        System.out.println(s1.get(10));

        s1.set("dd",10);
        System.out.println(s1);

        s1.remove(3);
        s1.remove("aa4");
        System.out.println(s1);

        System.out.println(s1.size);
        System.out.println(s1.isEmpty());
    }
}
